package com.atguigu.day06;

import com.atguigu.utils.ItemViewCountPerWindow;
import com.atguigu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;

// 需求：计算每过5分钟过去1小时的浏览次数最多的商品
// 思路：
// 第一步：计算出每个商品在每个窗口里的浏览次数，聚合结果是ItemViewCountPerWindow组成的一条流
//      1. 按照商品ID进行keyBy分区
//      2. 开窗，滑动窗口：窗口长度是1个小时，滑动距离是5分钟
//      3. 计算出每个窗口里每个商品ID的浏览次数：每个窗口中的数据的商品ID相同，且属于同一个窗口
// 第二步：将ItemViewCountPerWindow组成的流使用windowEnd或者windowStart分区，然后在每个分区使用ItemViewCountPerWindow的count字段降序排列
//      1. 将流按照windowEnd分区，将windowEnd相同的ItemViewCountPerWindow分到一个逻辑分区
//      2. 在每个分区按照浏览量count字段降序排序
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<UserBehavior> stream = env
                .readTextFile("/home/zuoyuan/flink0609/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] array = value.split(",");
                        return new UserBehavior(
                                array[0],
                                array[1],
                                array[2],
                                array[3],
                                Long.parseLong(array[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        // 第一步
        SingleOutputStreamOperator<ItemViewCountPerWindow> result1 = stream
                .keyBy(r -> r.itemId)
                .window(SlidingEventTimeWindows.of(
                        Time.hours(1),
                        Time.minutes(5)
                ))
                .aggregate(new CountAgg(), new WindowResult());

        // 第二步
        SingleOutputStreamOperator<String> result2 = result1
                // 每个逻辑分区都是同一个窗口里的ItemViewCountPerWindow统计值
                .keyBy(r -> r.windowEnd)
                .process(new TopN(3));

        result2.print();

        env.execute();
    }

    public static class TopN extends KeyedProcessFunction<Long, ItemViewCountPerWindow, String> {
        // 前n名的商品
        private int n;

        public TopN(int n) {
            this.n = n;
        }

        // 将相同窗口的ItemViewCountPerWindow放在一个ListState里面
        // 供排序使用
        private ListState<ItemViewCountPerWindow> listState;

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<ItemViewCountPerWindow>(
                            "item-view-count-per-window",
                            Types.POJO(ItemViewCountPerWindow.class)
                    )
            );
        }

        @Override
        public void processElement(ItemViewCountPerWindow value, Context ctx, Collector<String> out) throws Exception {
            listState.add(value);

            // 只要有一条大于windowEnd的水位线过来
            // 说明ItemViewCountPerWindow都到齐了
            // 定时器用来对ItemViewCountPerWindow进行排序
            // 由于到达的数据windowEnd都是一样的，所以定时器只会注册一次，不会重复注册
            ctx.timerService().registerEventTimeTimer(value.windowEnd + 1L);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            // 先将ListState中的数据放入ArrayList
            ArrayList<ItemViewCountPerWindow> arrayList = new ArrayList<>();
            for (ItemViewCountPerWindow e : listState.get()) arrayList.add(e);
            // ListState中的数据已经没用了，所以清空ListState，减小对内存的压力
            listState.clear();

            // 对arrayList进行排序
            arrayList.sort(new Comparator<ItemViewCountPerWindow>() {
                @Override
                public int compare(ItemViewCountPerWindow t1, ItemViewCountPerWindow t2) {
                    // 指定使用count字段降序排列
                    return t2.count.intValue() - t1.count.intValue();
                }
            });

            // 格式化成字符串输出
            StringBuilder result = new StringBuilder();
            result.append("===============================================\n");
            result.append("窗口结束时间：" + new Timestamp(timestamp - 1L));
            result.append("\n");
            for (int i = 0; i < n; i++) {
                ItemViewCountPerWindow tmp = arrayList.get(i);
                result.append("第" + (i + 1) + "名商品ID是：" + tmp.itemId + "，");
                result.append("浏览次数是：" + tmp.count);
                result.append("\n");
            }
            result.append("===============================================\n");
            out.collect(result.toString());
        }
    }

    public static class CountAgg implements AggregateFunction<UserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(UserBehavior value, Long accumulator) {
            return accumulator + 1L;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long, ItemViewCountPerWindow, String, TimeWindow> {
        @Override
        public void process(String s, Context context, Iterable<Long> elements, Collector<ItemViewCountPerWindow> out) throws Exception {
            out.collect(new ItemViewCountPerWindow(
                    s,
                    elements.iterator().next(),
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }
}
